<?php

namespace Fwadmin\Model;

use Think\Model;

class ContentModel extends Model {

    protected $_validate = array(
        array('category_id', 'require', '类别必须选择！', 1),
        array('order_id', 'require', '顺序编号必须填写！', 1),
        array('is_show', array(0, 1), '请设置是否显示！', 1, 'in')
    );

    /**
     * 搜索符合条件的记录
     * @param <type> $conditions 条件数组
     * @param string $order 排序字段
     * @param bool $mohu 是否模糊检索
     * @param bool $export 是否导出excel
     * @param int $pagesize 分页数
     */
    public function search($conditions, $order = 'order_id asc', $mohu = true, $export = false, $pagesize = 0) {
        $condition = 1;
        foreach ($conditions as $key => $val) {
            if ($key == 'btime') {
                $condition .= ' and create_time >= ' . strtotime($val);
            } elseif ($key == 'etime') {
                $condition .= ' and create_time <= ' . strtotime($val);
            } elseif ($key == 'path_id') {
                $condition .= " and path_id like '%" . $val . "%'";
            }elseif($key=='key'){
                $condition .= " and title like '%" . $val . "%'";
            } elseif ($key == 'category_id') {
                $condition .= " and category_id=$val";
            } elseif ((is_integer($val)) || (is_float($val))) {
                $condition .= ' and ' . $key . ' = ' . $val;
            } elseif (is_string($val)) {
                if ($mohu) {
                    $condition .= ' and ' . $key . ' like "%' . $val . '%"';
                } else {
                    $condition .= ' and ' . $key . ' = "' . $val . '"';
                }
            }
        }
        if (!$export) {
            $count = $this->where($condition)->count(); // 查询满足要求的总记录数
            if ($pagesize == 0) {
                $pagesize = C('PAGE_NUM');
            }
            $Page = new \Think\Page($count, $pagesize); // 实例化分页类 传入总记录数和每页显示的记录数
            //分页跳转的时候保证查询条件
            foreach ($conditions as $key => $val) {
                $Page->parameter[$key] = $val;
            }
            $show = $Page->show(); // 分页显示输出
            // 进行分页数据查诟 注意limit 方法癿参数要使用Page 类的属性
            $list = $this->where($condition)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
            //获得类别名称
            $M_C = M('CategoryContent');
            foreach ($list as $key => $row) {
                $list[$key]['category_name'] = $M_C->getFieldByCategoryId($row['category_id'], 'category_name');
            }
            return array(
                'list' => $list,
                'pageShow' => $show
            );
        } else {
            return $this->where($condition)->order($order)->select();
        }
    }

}
